import React, { useState } from 'react';
import {
  Box,
  Card,
  CardContent,
  Grid,
  TextField,
  Select,
  MenuItem,
  FormControl,
  InputLabel,
  Button,
  Typography,
  Divider,
  Switch,
  FormControlLabel,
  Chip,
  Alert,
  Autocomplete,
  InputAdornment,
} from '@mui/material';
import {
  Save as SaveIcon,
  Cancel as CancelIcon,
  Business as BusinessIcon,
} from '@mui/icons-material';
import { useNavigate } from 'react-router-dom';
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
import { useForm, Controller } from 'react-hook-form';
import { zodResolver } from '@hookform/resolvers/zod';
import { z } from 'zod';

import {
  CreateTenantRequest,
  Status,
  TenantSettings,
  SubscriptionPlan,
} from '@/types';
import { useAuth, useAppNotifications } from '@/stores';
import { tenantService } from '@/services/tenantService';
import { PageHeader } from '@/components/common/PageHeader';

// 表单验证模式
const tenantFormSchema = z.object({
  name: z.string().min(1, '租户名称不能为空').max(100, '租户名称不能超过100个字符'),
  code: z.string()
    .min(1, '租户编码不能为空')
    .max(50, '租户编码不能超过50个字符')
    .regex(/^[a-zA-Z0-9_-]+$/, '租户编码只能包含字母、数字、下划线和横线'),
  status: z.enum(['active', 'inactive', 'pending', 'suspended']),
  subscriptionPlanId: z.string().min(1, '请选择订阅套餐'),
  settings: z.object({
    maxUsers: z.number().min(1, '用户数限制不能少于1').max(10000, '用户数限制不能超过10000'),
    maxOrganizations: z.number().min(1, '组织数限制不能少于1').max(1000, '组织数限制不能超过1000'),
    maxStorage: z.number().min(100, '存储限制不能少于100MB').max(1000000, '存储限制不能超过1000GB'),
    allowCrossTenant: z.boolean(),
    dataRetentionDays: z.number().min(30, '数据保留期不能少于30天').max(3650, '数据保留期不能超过10年'),
    features: z.array(z.string()).optional(),
    customDomain: z.string().optional(),
    branding: z.object({
      logo: z.string().optional(),
      primaryColor: z.string().optional(),
      secondaryColor: z.string().optional(),
      favicon: z.string().optional(),
      companyName: z.string().optional(),
    }).optional(),
  }),
  contactInfo: z.object({
    email: z.string().email('请输入有效的邮箱地址').optional().or(z.literal('')),
    phone: z.string().optional(),
    address: z.string().optional(),
    website: z.string().url('请输入有效的网站地址').optional().or(z.literal('')),
  }).optional(),
  adminUserId: z.string().optional(),
  expiresAt: z.string().optional(),
});

type TenantFormData = z.infer<typeof tenantFormSchema>;

const TenantCreatePage: React.FC = () => {
  const navigate = useNavigate();
  const queryClient = useQueryClient();
  const { hasPermission } = useAuth();
  const { showToast } = useAppNotifications();

  const [isSubmitting, setIsSubmitting] = useState(false);

  // 表单控制
  const {
    control,
    handleSubmit,
    formState: { errors },
    watch,
    setValue,
  } = useForm<TenantFormData>({
    resolver: zodResolver(tenantFormSchema),
    defaultValues: {
      name: '',
      code: '',
      status: 'active',
      subscriptionPlanId: '',
      settings: {
        maxUsers: 100,
        maxOrganizations: 10,
        maxStorage: 1024, // 1GB
        allowCrossTenant: false,
        dataRetentionDays: 365,
        features: [],
        branding: {},
      },
      contactInfo: {
        email: '',
        phone: '',
        address: '',
        website: '',
      },
      adminUserId: '',
      expiresAt: '',
    },
  });

  // 监听租户名称变化，自动生成编码
  const tenantName = watch('name');
  React.useEffect(() => {
    if (tenantName) {
      const code = tenantName
        .toLowerCase()
        .replace(/[^a-z0-9\s]/g, '')
        .replace(/\s+/g, '_')
        .substring(0, 20);
      setValue('code', code);
    }
  }, [tenantName, setValue]);

  // 获取订阅套餐列表
  const { data: subscriptionPlans, isLoading: plansLoading } = useQuery({
    queryKey: ['subscription-plans'],
    queryFn: () => tenantService.getSubscriptionPlans(),
  });

  // 创建租户
  const createMutation = useMutation({
    mutationFn: tenantService.createTenant,
    onSuccess: (response) => {
      showToast({
        type: 'success',
        title: '创建成功',
        message: '租户已成功创建',
      });
      queryClient.invalidateQueries(['tenants']);
      navigate('/tenants');
    },
    onError: (error: any) => {
      showToast({
        type: 'error',
        title: '创建失败',
        message: error.message || '创建租户时发生错误',
      });
    },
  });

  // 提交表单
  const onSubmit = async (data: TenantFormData) => {
    if (!hasPermission('tenant.create')) {
      showToast({
        type: 'error',
        title: '权限不足',
        message: '您没有创建租户的权限',
      });
      return;
    }

    setIsSubmitting(true);
    try {
      await createMutation.mutateAsync(data as CreateTenantRequest);
    } finally {
      setIsSubmitting(false);
    }
  };

  // 可用功能选项
  const availableFeatures = [
    { id: 'analytics', label: '数据分析' },
    { id: 'api_access', label: 'API 访问' },
    { id: 'custom_branding', label: '自定义品牌' },
    { id: 'advanced_security', label: '高级安全' },
    { id: 'priority_support', label: '优先支持' },
    { id: 'data_export', label: '数据导出' },
    { id: 'sso', label: '单点登录' },
    { id: 'audit_logs', label: '审计日志' },
  ];

  return (
    <Box sx={{ p: 3 }}>
      <PageHeader
        title="创建租户"
        description="创建新的租户"
        breadcrumbs={[
          { label: '首页', path: '/' },
          { label: '租户管理', path: '/tenants' },
          { label: '创建租户' },
        ]}
      />

      <Card>
        <CardContent>
          <form onSubmit={handleSubmit(onSubmit)}>
            <Grid container spacing={3}>
              {/* 基本信息 */}
              <Grid item xs={12}>
                <Typography variant="h6" gutterBottom>
                  基本信息
                </Typography>
                <Divider sx={{ mb: 2 }} />
              </Grid>

              <Grid item xs={12} md={6}>
                <Controller
                  name="name"
                  control={control}
                  render={({ field }) => (
                    <TextField
                      {...field}
                      label="租户名称"
                      fullWidth
                      required
                      error={!!errors.name}
                      helperText={errors.name?.message}
                      InputProps={{
                        startAdornment: (
                          <InputAdornment position="start">
                            <BusinessIcon />
                          </InputAdornment>
                        ),
                      }}
                    />
                  )}
                />
              </Grid>

              <Grid item xs={12} md={6}>
                <Controller
                  name="code"
                  control={control}
                  render={({ field }) => (
                    <TextField
                      {...field}
                      label="租户编码"
                      fullWidth
                      required
                      error={!!errors.code}
                      helperText={errors.code?.message || '系统唯一标识，将根据租户名称自动生成'}
                    />
                  )}
                />
              </Grid>

              <Grid item xs={12} md={6}>
                <Controller
                  name="status"
                  control={control}
                  render={({ field }) => (
                    <FormControl fullWidth>
                      <InputLabel>状态</InputLabel>
                      <Select {...field} label="状态">
                        <MenuItem value="active">启用</MenuItem>
                        <MenuItem value="inactive">禁用</MenuItem>
                        <MenuItem value="pending">待审核</MenuItem>
                        <MenuItem value="suspended">暂停</MenuItem>
                      </Select>
                    </FormControl>
                  )}
                />
              </Grid>

              <Grid item xs={12} md={6}>
                <Controller
                  name="subscriptionPlanId"
                  control={control}
                  render={({ field }) => (
                    <FormControl fullWidth required>
                      <InputLabel>订阅套餐</InputLabel>
                      <Select
                        {...field}
                        label="订阅套餐"
                        error={!!errors.subscriptionPlanId}
                        disabled={plansLoading}
                      >
                        {subscriptionPlans?.data?.map((plan) => (
                          <MenuItem key={plan.id} value={plan.id}>
                            <Box sx={{ display: 'flex', alignItems: 'center', gap: 1 }}>
                              <Typography>{plan.name}</Typography>
                              <Chip
                                label={`¥${plan.price}/月`}
                                size="small"
                                color="primary"
                                variant="outlined"
                              />
                            </Box>
                          </MenuItem>
                        ))}
                      </Select>
                      {errors.subscriptionPlanId && (
                        <Typography variant="caption" color="error" sx={{ mt: 1 }}>
                          {errors.subscriptionPlanId.message}
                        </Typography>
                      )}
                    </FormControl>
                  )}
                />
              </Grid>

              <Grid item xs={12} md={6}>
                <Controller
                  name="expiresAt"
                  control={control}
                  render={({ field }) => (
                    <TextField
                      {...field}
                      label="到期时间"
                      type="date"
                      fullWidth
                      InputLabelProps={{ shrink: true }}
                      helperText="留空表示永不到期"
                    />
                  )}
                />
              </Grid>

              {/* 联系信息 */}
              <Grid item xs={12}>
                <Typography variant="h6" gutterBottom sx={{ mt: 2 }}>
                  联系信息
                </Typography>
                <Divider sx={{ mb: 2 }} />
              </Grid>

              <Grid item xs={12} md={6}>
                <Controller
                  name="contactInfo.email"
                  control={control}
                  render={({ field }) => (
                    <TextField
                      {...field}
                      label="邮箱地址"
                      type="email"
                      fullWidth
                      error={!!errors.contactInfo?.email}
                      helperText={errors.contactInfo?.email?.message}
                    />
                  )}
                />
              </Grid>

              <Grid item xs={12} md={6}>
                <Controller
                  name="contactInfo.phone"
                  control={control}
                  render={({ field }) => (
                    <TextField
                      {...field}
                      label="联系电话"
                      fullWidth
                    />
                  )}
                />
              </Grid>

              <Grid item xs={12} md={6}>
                <Controller
                  name="contactInfo.website"
                  control={control}
                  render={({ field }) => (
                    <TextField
                      {...field}
                      label="官方网站"
                      fullWidth
                      error={!!errors.contactInfo?.website}
                      helperText={errors.contactInfo?.website?.message}
                    />
                  )}
                />
              </Grid>

              <Grid item xs={12} md={6}>
                <Controller
                  name="contactInfo.address"
                  control={control}
                  render={({ field }) => (
                    <TextField
                      {...field}
                      label="地址"
                      fullWidth
                    />
                  )}
                />
              </Grid>

              {/* 配置设置 */}
              <Grid item xs={12}>
                <Typography variant="h6" gutterBottom sx={{ mt: 2 }}>
                  配置设置
                </Typography>
                <Divider sx={{ mb: 2 }} />
              </Grid>

              <Grid item xs={12} md={4}>
                <Controller
                  name="settings.maxUsers"
                  control={control}
                  render={({ field }) => (
                    <TextField
                      {...field}
                      label="用户数限制"
                      type="number"
                      fullWidth
                      required
                      error={!!errors.settings?.maxUsers}
                      helperText={errors.settings?.maxUsers?.message}
                    />
                  )}
                />
              </Grid>

              <Grid item xs={12} md={4}>
                <Controller
                  name="settings.maxOrganizations"
                  control={control}
                  render={({ field }) => (
                    <TextField
                      {...field}
                      label="组织数限制"
                      type="number"
                      fullWidth
                      required
                      error={!!errors.settings?.maxOrganizations}
                      helperText={errors.settings?.maxOrganizations?.message}
                    />
                  )}
                />
              </Grid>

              <Grid item xs={12} md={4}>
                <Controller
                  name="settings.maxStorage"
                  control={control}
                  render={({ field }) => (
                    <TextField
                      {...field}
                      label="存储限制 (MB)"
                      type="number"
                      fullWidth
                      required
                      error={!!errors.settings?.maxStorage}
                      helperText={errors.settings?.maxStorage?.message}
                    />
                  )}
                />
              </Grid>

              <Grid item xs={12} md={6}>
                <Controller
                  name="settings.dataRetentionDays"
                  control={control}
                  render={({ field }) => (
                    <TextField
                      {...field}
                      label="数据保留期 (天)"
                      type="number"
                      fullWidth
                      required
                      error={!!errors.settings?.dataRetentionDays}
                      helperText={errors.settings?.dataRetentionDays?.message}
                    />
                  )}
                />
              </Grid>

              <Grid item xs={12} md={6}>
                <Controller
                  name="settings.allowCrossTenant"
                  control={control}
                  render={({ field }) => (
                    <FormControlLabel
                      control={<Switch {...field} checked={field.value} />}
                      label="允许跨租户访问"
                    />
                  )}
                />
              </Grid>

              <Grid item xs={12}>
                <Controller
                  name="settings.features"
                  control={control}
                  render={({ field }) => (
                    <Autocomplete
                      multiple
                      options={availableFeatures}
                      getOptionLabel={(option) => option.label}
                      value={availableFeatures.filter(feature => 
                        field.value?.includes(feature.id)
                      )}
                      onChange={(_, newValue) => {
                        field.onChange(newValue.map(item => item.id));
                      }}
                      renderTags={(value, getTagProps) =>
                        value.map((option, index) => (
                          <Chip
                            key={option.id}
                            label={option.label}
                            {...getTagProps({ index })}
                          />
                        ))
                      }
                      renderInput={(params) => (
                        <TextField
                          {...params}
                          label="可用功能"
                          placeholder="选择功能特性..."
                        />
                      )}
                    />
                  )}
                />
              </Grid>

              {/* 操作按钮 */}
              <Grid item xs={12}>
                <Box sx={{ display: 'flex', gap: 2, justifyContent: 'flex-end', mt: 3 }}>
                  <Button
                    variant="outlined"
                    startIcon={<CancelIcon />}
                    onClick={() => navigate('/tenants')}
                    disabled={isSubmitting}
                  >
                    取消
                  </Button>
                  <Button
                    type="submit"
                    variant="contained"
                    startIcon={<SaveIcon />}
                    disabled={isSubmitting || !hasPermission('tenant.create')}
                  >
                    {isSubmitting ? '创建中...' : '创建租户'}
                  </Button>
                </Box>
              </Grid>
            </Grid>
          </form>
        </CardContent>
      </Card>
    </Box>
  );
};

export default TenantCreatePage;